/*
 * Copyright (c) 2015 LingoChamp Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yayawan.laomigame;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.google.android.material.tabs.TabLayout;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadConnectListener;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.IDownloadSpeed;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.jiafan.dy.R;
import com.yayawan.utils.Sputils;
import com.yayawan.utils.Yayalog;


import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jacksgong on 1/9/16.
 */
public class TasksManagerActivity extends AppCompatActivity {

    private static TaskItemAdapter adapter;

    private static Activity mActivity;
    private  static String Tag="taskmanager";
    private static int installposition=1000;

    String basefilepath= android.os.Environment.getExternalStorageDirectory().getPath();

    InitApkBroadCastReceiver mInitApkBroadCastReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity=this;
        setContentView(R.layout.activity_tasks_manager_demo);

        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter = new TaskItemAdapter());
        TasksManager.getImpl().onCreate(new WeakReference<>(this));
        Intent intent = getIntent();
        String gameid = intent.getStringExtra("gameid");
        if (!TextUtils.isEmpty(gameid)){
            gameid="123";
            String gamename= intent.getStringExtra("gamename");
            String gameurl= intent.getStringExtra("gameurl");
            String gameiconurl= intent.getStringExtra("gameiconurl");
            String gamepackagename= intent.getStringExtra("gamepackagename");

            if (TextUtils.isEmpty(gamepackagename)){
                gamepackagename="com.xxx";
            }else {

            }
            Yayalog.loger(gamepackagename);
            TasksManager.getImpl().addTask(Integer.parseInt(gameid),gamename,gameurl,gameiconurl, gamepackagename);
            Log.d("taskmanager","gameid"+gameurl);
        }

         mInitApkBroadCastReceiver=   new InitApkBroadCastReceiver();

        IntentFilter intentFilter =new IntentFilter();

        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);

        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);

        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);

        intentFilter.addDataScheme("package");

        registerReceiver(mInitApkBroadCastReceiver, intentFilter);

        //返回响应
        ImageView im=findViewById(R.id.ima_pre);
        im.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void postNotifyDataChanged() {
        if (adapter != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                    }
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        TasksManager.getImpl().onDestroy();
        adapter = null;
        FileDownloader.getImpl().pauseAll();
        if (mInitApkBroadCastReceiver!=null){
            unregisterReceiver(mInitApkBroadCastReceiver);
        }

        super.onDestroy();
    }


    // ============================================================================ view adapter ===

    private static class TaskItemViewHolder extends RecyclerView.ViewHolder {

        public TaskItemViewHolder(View itemView) {
            super(itemView);
            assignViews();
        }

        private View findViewById(final int id) {
            return itemView.findViewById(id);
        }

        /**
         * viewHolder position
         */
        private int position;
        /**
         * download id
         */
        private int id;

        public void update(final int id, final int position) {
            this.id = id;
            this.position = position;
        }


        public void updateDownloaded() {
            taskPb.setMax(1);
            taskPb.setProgress(1);

            taskStatusTv.setText(R.string.tasks_manager_demo_status_completed);
//             <string name="start">开始</string>
//    <string name="pause">暂停</string>
//    <string name="delete">删除</string>
            taskActionBtnstart.setText("删除");
            taskActionBtnstart.setBackgroundResource(R.drawable.downloaddelete);
        }

        public void updateNotDownloaded(final int status, final long sofar, final long total) {
            if (sofar > 0 && total > 0) {
                final float percent = sofar
                        / (float) total;
                taskPb.setMax(100);
                taskPb.setProgress((int) (percent * 100));
            } else {
                taskPb.setMax(1);
                taskPb.setProgress(0);
            }

            switch (status) {
                case FileDownloadStatus.error:
                    taskStatusTv.setText(R.string.tasks_manager_demo_status_error);
                    break;
                case FileDownloadStatus.paused:
                    taskStatusTv.setText(R.string.tasks_manager_demo_status_paused);
                    break;
                default:
                    taskStatusTv.setText(R.string.tasks_manager_demo_status_not_downloaded);
                    break;
            }
            taskActionBtnstart.setText("开始");
            taskActionBtnstart.setBackgroundResource(R.drawable.downloadstart);
        }

        public void updateDownloading(final int status, final long sofar, final long total) {
            final float percent = sofar
                    / (float) total;
            taskPb.setMax(100);
            taskPb.setProgress((int) (percent * 100));

            switch (status) {
                case FileDownloadStatus.pending:
                    taskStatusTv.setText(R.string.tasks_manager_demo_status_pending);
                   // taskStatusjindu.setText(sofar+"/"+total);
                    break;
                case FileDownloadStatus.started:
                    taskStatusTv.setText(R.string.tasks_manager_demo_status_started);

                    break;
                case FileDownloadStatus.connected:
                    taskStatusTv.setText(R.string.tasks_manager_demo_status_connected);
                    break;
                case FileDownloadStatus.progress:
                    taskStatusTv.setText(R.string.tasks_manager_demo_status_progress);
                    float nowdata = sofar
                            / 1024/1024;
                    float nowtotal = total
                            / 1024/1024;
                    taskStatusjindu.setText(nowdata+"M"+"/"+nowtotal+"M");
                    break;
                default:
                    taskStatusTv.setText(R.string.tasks_manager_demo_status_downloading);
                    break;
            }

            taskActionBtnstart.setText(R.string.pause);
            taskActionBtnstart.setBackgroundResource(R.drawable.downloadstop);
        }

        private TextView taskNameTv;
        private TextView taskStatusTv;
        private ProgressBar taskPb;
        private Button taskActionBtnstart;
        private Button taskActionBtninstall;
        private TextView taskStatusjindu;
        private ImageView gameiconIv;

        private void assignViews() {
            taskNameTv = (TextView) findViewById(R.id.task_name_tv);
            taskStatusTv = (TextView) findViewById(R.id.task_status_tv);
            taskPb = (ProgressBar) findViewById(R.id.task_pb);
            taskActionBtnstart = (Button) findViewById(R.id.task_action_btn_start);
            taskActionBtninstall = (Button) findViewById(R.id.task_action_btn_install);
            taskStatusjindu = (TextView) findViewById(R.id.task_status_tv_jindu);
            gameiconIv= (ImageView) findViewById(R.id.game_icon);
        }

    }
    public static Integer position=-1;

    public static String  filepath="";

    public static String  packagename="";

    public static void deleItem(String pagename){

        if (pagename.equals(packagename)){
            //Log.d(Tag,"准备删除包地址："+filepath);
            Yayalog.loger("准备删除包地址："+filepath);

               // TasksManager.getImpl().removeTaskForViewHolder(TasksManager.getImpl().get(position).getId());
                TasksManager.getImpl().deletaskViewHolder(TasksManager.getImpl().getIdBypackagename(packagename));
            if (!TextUtils.isEmpty(filepath)){

                if (new File(filepath).exists()){
                    boolean fileisdele=  new File(filepath).delete();
                    if (fileisdele){
                        //  Log.d(Tag,"删除包成功，删除地址："+filepath);
                        Yayalog.loger("删除包成功，删除地址："+filepath);
                        filepath="";
                    }

                }else {
                    filepath="";
                }
            }
        }

    }
    private static class TaskItemAdapter extends RecyclerView.Adapter<TaskItemViewHolder> {

        private FileDownloadListener taskDownloadListener = new FileDownloadSampleListener() {

            private TaskItemViewHolder checkCurrentHolder(final BaseDownloadTask task) {

                final TaskItemViewHolder tag = (TaskItemViewHolder) task.getTag();

                    Log.d(Tag,task.getTag()+""+task.getId()+" checkCurrentHolder");

                    if (tag.id != task.getId()) {
                        return null;
                    }
               // }
                return tag;
            }

            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                super.pending(task, soFarBytes, totalBytes);

                final TaskItemViewHolder tag = checkCurrentHolder(task);
                if (tag == null) {
                    return;
                }

                tag.updateDownloading(FileDownloadStatus.pending, soFarBytes
                        , totalBytes);
                tag.taskStatusTv.setText(R.string.tasks_manager_demo_status_pending);
            }

            @Override
            protected void started(BaseDownloadTask task) {
                super.started(task);
                final TaskItemViewHolder tag = checkCurrentHolder(task);
                if (tag == null) {
                    return;
                }

                tag.taskStatusTv.setText(R.string.tasks_manager_demo_status_started);
            }

            @Override
            protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                super.connected(task, etag, isContinue, soFarBytes, totalBytes);
                final TaskItemViewHolder tag = checkCurrentHolder(task);
                if (tag == null) {
                    return;
                }

                tag.updateDownloading(FileDownloadStatus.connected, soFarBytes
                        , totalBytes);
                tag.taskStatusTv.setText(R.string.tasks_manager_demo_status_connected);
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                super.progress(task, soFarBytes, totalBytes);
                final TaskItemViewHolder tag = checkCurrentHolder(task);
                if (tag == null) {
                    return;
                }

                tag.updateDownloading(FileDownloadStatus.progress, soFarBytes
                        , totalBytes);
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                super.error(task, e);
                final TaskItemViewHolder tag = checkCurrentHolder(task);
                if (tag == null) {
                    return;
                }

                tag.updateNotDownloaded(FileDownloadStatus.error, task.getLargeFileSoFarBytes()
                        , task.getLargeFileTotalBytes());
                TasksManager.getImpl().removeTaskForViewHolder(task.getId());
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                super.paused(task, soFarBytes, totalBytes);
                final TaskItemViewHolder tag = checkCurrentHolder(task);
                if (tag == null) {
                    return;
                }

                tag.updateNotDownloaded(FileDownloadStatus.paused, soFarBytes, totalBytes);
                tag.taskStatusTv.setText(R.string.tasks_manager_demo_status_paused);
                TasksManager.getImpl().removeTaskForViewHolder(task.getId());
            }

            @Override
            protected void completed(BaseDownloadTask task) {
                super.completed(task);
                final TaskItemViewHolder tag = checkCurrentHolder(task);
                if (tag == null) {
                    return;
                }

                int k=  Sputils.getSPint(Constant.ISAUTOINSTALLAPK,1,mActivity);
                if (k==1){

                    Yayalog.loger("installProcess baoming"+TasksManager.getImpl().getPackagenamebyid(task.getId()));

                    installProcess(mActivity,new File(task.getPath()), TasksManager.getImpl().getPackagenamebyid(task.getId()),task.getId());
                }

                tag.updateDownloaded();

                TasksManager.getImpl().removeTaskForViewHolder(task.getId());


            }
        };



        private View.OnClickListener taskActionOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getTag() == null) {
                    return;
                }


                TaskItemViewHolder holder = (TaskItemViewHolder) v.getTag();

                CharSequence  action = ((TextView) v).getText();
                Log.d(Tag,action.toString());
                if (action.equals(v.getResources().getString(R.string.pause))) {
                    // to pause
                    FileDownloader.getImpl().pause(holder.id);
                } else if (action.equals(v.getResources().getString(R.string.start))) {
                    // to start
                    // to start
                    //tag
                    final TasksManagerModel model = TasksManager.getImpl().get(holder.position);
                    Log.d(Tag,model.getName());
                    final BaseDownloadTask task = FileDownloader.getImpl().create(model.getUrl())
                            .setPath(model.getPath())
                            .setCallbackProgressTimes(100)

                            .setListener(taskDownloadListener);

                    TasksManager.getImpl()
                            .addTaskForViewHolder(task);

                    TasksManager.getImpl()
                            .updateViewHolder(holder.id, holder);

                    task.start();
                } else if (action.equals(v.getResources().getString(R.string.delete))) {
                    // to delete
                    new File(TasksManager.getImpl().get(holder.position).getPath()).delete();
                    holder.taskActionBtnstart.setEnabled(true);

                    holder.updateNotDownloaded(FileDownloadStatus.INVALID_STATUS, 0, 0);
                    TasksManager.getImpl().removeTaskForViewHolder(TasksManager.getImpl().get(holder.position).getId());
                    TasksManager.getImpl().deletaskViewHolder(TasksManager.getImpl().get(holder.position).getId());
                }else if (action.equals("安装")) {
                    // anzhuang


                    //new File(TasksManager.getImpl().get(holder.position).getPath());

                    Yayalog.loger("点击安装的包名+"+TasksManager.getImpl().get(holder.position).getPackagename());
                    installProcess(mActivity,new File(TasksManager.getImpl().get(holder.position).getPath()),TasksManager.getImpl().get(holder.position).getPackagename(),holder.position);
                }
            }
        };



        @Override
        public TaskItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            TaskItemViewHolder holder = new TaskItemViewHolder(
                    LayoutInflater.from(
                            parent.getContext())
                            .inflate(R.layout.item_tasks_manager, parent, false));

            holder.taskActionBtnstart.setOnClickListener(taskActionOnClickListener);
            holder.taskActionBtninstall.setOnClickListener(taskActionOnClickListener);
            return holder;
        }

        @Override
        public void onBindViewHolder(TaskItemViewHolder holder, int position) {
            final TasksManagerModel model = TasksManager.getImpl().get(position);

            holder.update(model.getId(), position);
            holder.taskActionBtnstart.setTag(holder);
            holder.taskActionBtninstall.setTag(holder);
            holder.taskNameTv.setText(model.getName());

            TasksManager.getImpl()
                    .updateViewHolder(holder.id, holder);

            holder.taskActionBtnstart.setEnabled(true);
            holder.taskActionBtninstall.setEnabled(true);

            if (TasksManager.getImpl().isReady()) {
                final int status = TasksManager.getImpl().getStatus(model.getId(), model.getPath());
                if (status == FileDownloadStatus.pending || status == FileDownloadStatus.started ||
                        status == FileDownloadStatus.connected) {
                    // start task, but file not created yet
                    holder.updateDownloading(status, TasksManager.getImpl().getSoFar(model.getId())
                            , TasksManager.getImpl().getTotal(model.getId()));
                } else if (!new File(model.getPath()).exists() &&
                        !new File(FileDownloadUtils.getTempPath(model.getPath())).exists()) {
                    // not exist file
                    holder.updateNotDownloaded(status, 0, 0);
                    final TasksManagerModel model1 = TasksManager.getImpl().get(holder.position);
                    Log.d(Tag,model.getName());
                    final BaseDownloadTask task = FileDownloader.getImpl().create(model1.getUrl())
                            .setPath(model1.getPath())
                            .setCallbackProgressTimes(100)
                            .setListener(taskDownloadListener);

                    TasksManager.getImpl()
                            .addTaskForViewHolder(task);

                    TasksManager.getImpl()
                            .updateViewHolder(holder.id, holder);

                    task.start();

                } else if (TasksManager.getImpl().isDownloaded(status)) {
                    // already downloaded and exist
                    holder.updateDownloaded();
                } else if (status == FileDownloadStatus.progress) {
                    // downloading
                    holder.updateDownloading(status, TasksManager.getImpl().getSoFar(model.getId())
                            , TasksManager.getImpl().getTotal(model.getId()));
                } else {
                    // not start
                    holder.updateNotDownloaded(status, TasksManager.getImpl().getSoFar(model.getId())
                            , TasksManager.getImpl().getTotal(model.getId()));
                }
            } else {
                holder.taskStatusTv.setText(R.string.tasks_manager_demo_status_loading);

                //Glide.with(mActivity).load(model.iconurl).placeholder(R.drawable.testicon).into(holder.gameiconIv);
                //holder.gameiconurl.setImageDrawable();
                holder.taskActionBtnstart.setEnabled(false);
            }
            Glide.with(mActivity).load(model.iconurl).listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    Log.d("Wain","加载失败 errorMsg:"+(e!=null?e.getMessage():"null"));
                    return false;
                }

                @Override
                public boolean onResourceReady(final Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    Log.d("Wain","成功  Drawable Name:"+resource.getClass().getCanonicalName());
                    return false;
                }
            })
                    .into(holder.gameiconIv);
        }

        @Override
        public int getItemCount() {
            return TasksManager.getImpl().getTaskCounts();
        }
    }
    static File   apkfile;
    //安装应用的流程
    @TargetApi(26)
    private static void installProcess(final Activity mac,File mapkfile,String kpackagename,int kposition) {


        position=kposition;
        filepath=mapkfile.getAbsolutePath();
        packagename=kpackagename;

        apkfile=mapkfile;
        File apk = mapkfile;
        if (!apk.exists()) {
            return;
        }
        boolean haveInstallPermission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先获取是否有安装未知来源应用的权限
            haveInstallPermission = mac.getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {//没有权限
                AlertDialog.Builder builder = new AlertDialog.Builder(mac);
                builder.setTitle("安装应用需要打开未知来源权限，请去设置中开启权限");
                builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            permissonTempFile=apk;
                            startInstallPermissionSettingActivity(mac);
                        }
                    }
                });
                builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.create().show();
                return;
            }
        }
        //有权限，开始安装应用程序
        installApk(apk,mac);
    }


     static File permissonTempFile;

    private static void startInstallPermissionSettingActivity(Activity mac) {
        Uri packageURI = Uri.parse("package:" + mac.getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        mac.startActivityForResult(intent, 10086);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==10086){
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被用户同意，可以做你要做的事情了。
                if (permissonTempFile!=null){
                    installApk(permissonTempFile,mActivity);
                }
            }
        }
    }

    //安装应用
    private static void installApk(File apk,Activity mac) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive");
        } else {//Android7.0之后获取uri要用contentProvider
            Uri uri = getUriFromFile(mac.getBaseContext(), apk);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mac.getBaseContext().startActivity(intent);
    }
    public static Uri getUriFromFile(Context context, File file) {
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = DgameFileProvider.getUriForFile(context,
                    context.getPackageName()+":yyw", file);//通过FileProvider创建一个content类型的Uri
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }
    // ============================================================================ controller ====


    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);

    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
    }

    public static class TasksManager {
        private final static class HolderClass {
            private final static TasksManager INSTANCE
                    = new TasksManagerActivity.TasksManager();
        }

        public static TasksManager getImpl() {
            return HolderClass.INSTANCE;
        }

        private TasksManagerDBController dbController;
        private List<TasksManagerModel> modelList;

        private TasksManager() {
            dbController = new TasksManagerDBController();
            modelList = dbController.getAllTasks();

           // initDemo();
        }



        private SparseArray<BaseDownloadTask> taskSparseArray = new SparseArray<>();

        public void addTaskForViewHolder(final BaseDownloadTask task) {
            Log.d(Tag, "添加task");
            taskSparseArray.put(task.getId(), task);
        }

        public void removeTaskForViewHolder(final int id) {



            taskSparseArray.remove(id);
        }
        public void deletaskViewHolder(final int id) {

            TasksManagerModel model = getById(id);
            boolean b = dbController.deleTask(id);
            if (b){
                Log.d(Tag, "删除task成功");
                Yayalog.loger("删除task成功");
            }
            if (model != null) {

                if (model != null) {
                    modelList.remove(model);
                    adapter.notifyDataSetChanged();
                }
            }

            //taskSparseArray.remove(id);
        }

        public String getPackagenamebyid( int id) {

            TasksManagerModel model = getById(id);
          return model.getPackagename();

        }

        public void updateViewHolder(final int id, final TaskItemViewHolder holder) {
            Log.d(Tag, id+"添加");
            final BaseDownloadTask task = taskSparseArray.get(id);

            if (task == null) {
                return;
            }else {
                Log.d(Tag, taskSparseArray.size()+taskSparseArray.get(id).getPath());
            }
            Log.d(Tag, id+"setTagholder添加");
            task.setTag(holder);
        }

        public void releaseTask() {
            taskSparseArray.clear();
        }

        private FileDownloadConnectListener listener;

        private void registerServiceConnectionListener(final WeakReference<TasksManagerActivity>
                                                               activityWeakReference) {
            if (listener != null) {
                FileDownloader.getImpl().removeServiceConnectListener(listener);
            }

            listener = new FileDownloadConnectListener() {

                @Override
                public void connected() {
                    if (activityWeakReference == null
                            || activityWeakReference.get() == null) {
                        return;
                    }

                    activityWeakReference.get().postNotifyDataChanged();
                }

                @Override
                public void disconnected() {
                    if (activityWeakReference == null
                            || activityWeakReference.get() == null) {
                        return;
                    }

                    activityWeakReference.get().postNotifyDataChanged();
                }
            };

            FileDownloader.getImpl().addServiceConnectListener(listener);
        }

        private void unregisterServiceConnectionListener() {
            FileDownloader.getImpl().removeServiceConnectListener(listener);
            listener = null;
        }

        public void onCreate(final WeakReference<TasksManagerActivity> activityWeakReference) {
            if (!FileDownloader.getImpl().isServiceConnected()) {
                FileDownloader.getImpl().bindService();
                registerServiceConnectionListener(activityWeakReference);
            }
        }

        public void onDestroy() {
            unregisterServiceConnectionListener();
            releaseTask();
        }

        public boolean isReady() {
            return FileDownloader.getImpl().isServiceConnected();
        }

        public TasksManagerModel get(final int position) {
            return modelList.get(position);
        }

        public TasksManagerModel getById(final int id) {
            for (TasksManagerModel model : modelList) {
                if (model.getId() == id) {
                    return model;
                }
            }

            return null;
        }

        public int getIdBypackagename( String mpackagename) {
            for (TasksManagerModel model : modelList) {
                if (model.getPackagename() .equals(mpackagename) ) {
                    return model.getId();
                }
            }

            return -1;
        }

        /**
         * @param status Download Status
         * @return has already downloaded
         * @see FileDownloadStatus
         */
        public boolean isDownloaded(final int status) {
            return status == FileDownloadStatus.completed;
        }

        public int getStatus(final int id, String path) {
            return FileDownloader.getImpl().getStatus(id, path);
        }

        public long getTotal(final int id) {
            return FileDownloader.getImpl().getTotal(id);
        }

        public long getSoFar(final int id) {
            return FileDownloader.getImpl().getSoFar(id);
        }

        public int getTaskCounts() {
            return modelList.size();
        }

//        public TasksManagerModel addTask(final String url) {
//            return addTask(url, createPath(url));
//        }

        public TasksManagerModel addTask(final int gameid,final String gamename,final String url, final String iconurl,String packagename) {
            String path=  createPath(url);
            if (TextUtils.isEmpty(url) || TextUtils.isEmpty(path)) {
                return null;
            }
            final int id = FileDownloadUtils.generateId(url, path);
            TasksManagerModel model = getById(id);
            if (model != null) {
                return model;
            }
            final TasksManagerModel newModel = dbController.addTask(id, gamename,url,iconurl,path,packagename);
            if (newModel != null) {
                modelList.add(newModel);
              //  adapter.notifyDataSetChanged();
            }




            return newModel;
        }

        public String createPath(final String url) {
            if (TextUtils.isEmpty(url)) {
                return null;
            }

            return FileDownloadUtils.getDefaultSaveFilePath(url);
        }
    }

    private static class TasksManagerDBController {
        public final static String TABLE_NAME = "tasksmanger";
        private final SQLiteDatabase db;

        private TasksManagerDBController() {
            TasksManagerDBOpenHelper openHelper = new TasksManagerDBOpenHelper(mActivity.getApplicationContext());

            db = openHelper.getWritableDatabase();
        }

        public List<TasksManagerModel> getAllTasks() {
            final Cursor c = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);

            final List<TasksManagerModel> list = new ArrayList<>();
            try {
                if (!c.moveToLast()) {
                    return list;
                }

                do {
                    TasksManagerModel model = new TasksManagerModel();
                    model.setId(c.getInt(c.getColumnIndex(TasksManagerModel.ID)));
                    model.setName(c.getString(c.getColumnIndex(TasksManagerModel.NAME)));
                    model.setUrl(c.getString(c.getColumnIndex(TasksManagerModel.URL)));
                    model.setPath(c.getString(c.getColumnIndex(TasksManagerModel.PATH)));
                    model.setIconurl(c.getString(c.getColumnIndex(TasksManagerModel.ICONURL)));
                    model.setIconurl(c.getString(c.getColumnIndex(TasksManagerModel.PACKAGENAME)));
                    list.add(model);
                } while (c.moveToPrevious());
            } finally {
                if (c != null) {
                    c.close();
                }
            }

            return list;
        }

        public TasksManagerModel addTask(final int gameid,final String gamename,final String url, final String iconurl,final String path,final String packagename) {
            if (TextUtils.isEmpty(url) || TextUtils.isEmpty(path)) {
                return null;
            }

            // have to use FileDownloadUtils.generateId to associate TasksManagerModel with FileDownloade
            final int id = FileDownloadUtils.generateId(url, path);
            TasksManagerModel model = new TasksManagerModel();
            model.setId(id);
            model.setName(gamename);
            model.setUrl(url);
            model.setPath(path);
            model.setIconurl(iconurl);
            model.setPackagename(packagename);

            final boolean succeed = db.insert(TABLE_NAME, null, model.toContentValues()) != -1;
            return succeed ? model : null;
        }
        public boolean  deleTask(final int id) {


            // have to use FileDownloadUtils.generateId to associate TasksManagerModel with FileDownloade

            TasksManagerModel model = new TasksManagerModel();
            model.setId(id);


            final boolean succeed =  db.delete(TABLE_NAME,"id = ?",new String[]{id+""})!= -1;
            return  succeed;

        }

    }

    // ----------------------- model
    private static class TasksManagerDBOpenHelper extends SQLiteOpenHelper {
        public final static String DATABASE_NAME = "tasksmanager.db";
        public final static int DATABASE_VERSION = 4;

        public TasksManagerDBOpenHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }


        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL("CREATE TABLE IF NOT EXISTS "
                    + TasksManagerDBController.TABLE_NAME
                    + String.format(
                    "("
                            + "%s INTEGER PRIMARY KEY, " // id, download id
                            + "%s VARCHAR, " // name
                            + "%s VARCHAR, " // url
                            + "%s VARCHAR, " // path
                            + "%s VARCHAR, " // iconurl
                            + "%s VARCHAR " // packagename
                            + ")"
                    , TasksManagerModel.ID
                    , TasksManagerModel.NAME
                    , TasksManagerModel.URL
                    , TasksManagerModel.PATH
                    , TasksManagerModel.ICONURL
                    , TasksManagerModel.PACKAGENAME

            ));
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            if (oldVersion == 1 && newVersion == 3) {

                db.delete(TasksManagerDBController.TABLE_NAME, null, null);


            }

            if (oldVersion<4){
                Toast.makeText(mActivity,"请卸载重新安装新版本",Toast.LENGTH_SHORT).show();
            }
        }
    }

    private static class TasksManagerModel {
        public final static String ID = "id";
        public final static String NAME = "name";
        public final static String URL = "url";
        public final static String PATH = "path";
        public final static String ICONURL = "iconurl";
        public final static String PACKAGENAME = "packagename";
        private int id;
        private String name;
        private String url;
        private String path;
        private String iconurl;
        private String packagename;



        public String getPackagename() {
            return packagename;
        }

        public void setPackagename(String packagename) {
            this.packagename = packagename;
        }


        public String getIconurl() {
            return iconurl;
        }

        public void setIconurl(String iconurl) {
            this.iconurl = iconurl;
        }

       

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public ContentValues toContentValues() {
            ContentValues cv = new ContentValues();
            cv.put(ID, id);
            cv.put(NAME, name);
            cv.put(URL, url);
            cv.put(PATH, path);
            cv.put(ICONURL, iconurl);
            cv.put(PACKAGENAME, packagename);
            return cv;
        }
    }


}
